<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <div slot="toolbar" v-if="!pkId">
            <a-checkbox v-model="isContinue">{{i18n('form.continueToCreateTheNext','继续创建下一个') }}</a-checkbox>
        </div>
        <rx-layout>
            <div slot="center">
                <a-form :form="form">
                    <a-form-item style="display: none;">
                        <a-input v-decorator="['groupId']"/>
                        <a-input v-decorator="['parentId']"/>
                        <a-input v-decorator="['dimId']"/>
                        <a-input v-decorator="['status']"/>
                        <a-input v-decorator="['tenantId']"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$comi18('business.groupName','用户组名称')">
                        <rx-input-i18n :placeholder="$comi18('business.groupName','用户组全称')" :isDecorator="true"
                                     v-decorator="['i18nJson', {rules: [{required: true, message: $comi18('business.groupName','用户组名称','input')}]}]"
                        />
                    </a-form-item>

                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.groupKey','组KEY')">
                        <a-input :placeholder="i18n('form.groupKey','组KEY')"
                                 v-decorator="['key', {rules: [{required: true, message: i18n('form.userGroupKey','用户组KEY','input')}]}]"/>
                    </a-form-item>

                    <a-form-item v-if="supportGrade && dimId == 1" :labelCol="labelCol" :wrapperCol="wrapperCol"
                                 :label="i18n('form.organizationType','组织类型')" >
                        <a-select :placeholder="i18n('form.organizationType','组织类型')"
                                  v-decorator="['type', {rules: [{required: true, message: i18n('form.organizationType','组织类型','select')}]}]">
                            <a-select-option :value="1">
                                {{i18n('form.unit','单位')}}
                            </a-select-option>
                            <a-select-option :value="2">
                                {{i18n('form.department','部门')}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item v-show="rankData.length>0" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.levelValue','所属等级值')">
                        <a-select :placeholder="i18n('form.levelValue','所属等级值')" v-decorator="['rankId']" :options="rankData"
                                  :getPopupContainer="p=>p.parentNode"
                                  :allowClear="true"
                        ></a-select>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.describe','描述')">
                        <a-textarea :placeholder="i18n('form.describe','描述')" v-decorator="['descp']"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.sortNumber','排序号')">
                        <a-input-number :max="1000000" :min="0" :placeholder="i18n('form.sortNumber','排序号')"
                                        v-decorator="['sn', {initialValue:1,rules: [{required: true, message: i18n('form.sortNumber','排序号','input')}]}]"/>
                    </a-form-item>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import OsGroupApi from '@/api/user/org/osGroup'
import OsRankTypeApi from '@/api/user/org/osRankType'
import {BaseForm, RxDialog,Util } from "@lowcode/jpaas-common-lib"

export default {
    name: 'OsGroupEdit',
    mixins: [BaseForm],
    props: ["parentId", "dimId", "isGrade", "tenantId", "supportGrade","layerid","destroy","updateData","tableData"],
    components: {
        RxDialog,
    },
    data() {
        return {
            title: '',
            rankData: [],
            labelCol: {span: 5},
            wrapperCol: {span: 16},
            isContinue:false,
            link:{}
        }
    },
    created() {
        this.initRankData()
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"osGroup",key);
        },
        initRankData() {
            let self=this;
            var obj = {Q_DIM_ID__S_EQ: this.dimId};
            if (this.tenantId) {
                obj.tenantId = this.tenantId;
            }
            const params = {params: obj}
            OsRankTypeApi.query(params).then(res => {
                this.rankData = res.data.map(rank => ({
                    title: rank.name,
                    value: rank.rkId,
                    level: rank.level
                }))
            })
        },
        get(id) {
            return OsGroupApi.getOsGroup(id);
        },
        save(values) {
            if (this.isGrade) {
                values.isGrade = this.isGrade;
            }
            if (this.tenantId) {
                values.tenantId = this.tenantId;
            }
            if (this.rankData.length>0){
                var level;
                for (var l=0;l<this.rankData.length;l++){
                    if (this.rankData[l].value==values.rankId){
                        level=this.rankData[l].level
                    }
                }
                values.rankLevel=level;
            }
            return OsGroupApi.saveOsGroup(values);
        },
        onload_(data) {
            this.mdl = Object.assign({
                parentId: this.parentId == null ? "0" : this.parentId,
                dimId: this.dimId,
                status: 'ENABLED'
            });
            if (data && data.rankId){
              this.mdl.rankId=data.rankId
            }
            this.form.setFieldsValue(this.mdl);
        },
        handleSubmit(vm) {
            this.form.validateFields((err, values) => {
                if (err) {
                    vm.loading = false;
                    return;
                }
                let routeId = this.$route ?this.$route.params.id:"";
                if (this.pkId) {
                    values.pkId = this.pkId;
                } else {
                    if (routeId && routeId != "add") {
                        values.pkId = routeId;
                    } else {
                        values.pkId = ''
                    }
                }
                this.confirmLoading = true;
                if (this.validForm) {
                    var flag = this.validForm(values);
                    if (!flag) {
                        vm.loading = false;
                        return;
                    }
                }
                let appId=this.curApp.appId;
                if(appId && !this.pkId){
                    values.appId=appId;
                }
                this.onSubmit(values);
                let _self = this ;
                this.save(values,vm).then(res => {
                    if (res.success && res.code == 200) {
                        //返回结果数据。
                        this.resultData = res.data;
                        //新增
                        if(!_self.pkId){
                            _self.updateData(_self.tableData, res.data, res.data.parentId,true);
                        }else {
                            _self.updateTreeData(_self.tableData, res.data);
                        }
                        //是否添加下一个
                        if(_self.isContinue){
                            _self.form.resetFields();
                            _self.onload_();
                        }else {
                            let _layerid = this.layerid;//根据判断有没有弹窗的id来判断是不是弹窗方式打开的页面 ;
                            if(_self.showType != "newPage"){
                                if (_layerid) {
                                    Util.closeWindow(this, "ok",res.data);
                                } else {
                                    this.$bus.emit("closeTab", {action: "current",tableData:res.data});
                                }
                            }
                        }
                        vm.loading = false;
                    }
                }).finally(() => {
                    this.confirmLoading = false;
                    vm.loading = false;
                })
            })
        },
        cancel() {
            let _layerid = this.layerid;//根据判断有没有弹窗的id来判断是不是弹窗方式打开的页面 ;
            if (_layerid) {
                Util.closeWindow(this, "cancel",this.tableData);
            } else {
                this.$bus.emit("closeTab", {action: "current",tableData:this.tableData})
            }
        },
        //更新数据到树结构中
        updateTreeData(treeData,data){
            if(!treeData || treeData.length==0){
                treeData.push(data);
                return;
            }
            for (let i = 0; i < treeData.length; i++) {
                if(treeData[i].groupId==data.groupId){
                    data.childAmount = treeData[i].childAmount;
                    data.children = treeData[i].children;
                    treeData[i]=data;
                    return;
                }else {
                    if(treeData[i].children && treeData[i].children.length>0){
                        this.updateTreeData(treeData[i].children,data);
                    }
                }
            }
        }
    }
}
</script>
